<script setup>
import {computed, nextTick, onUpdated, reactive, ref, watch} from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  tabs: {
    type: Array,
    required: true
  },
  idKey: String,
  titleKey: String,
})
const emits = defineEmits(['tab-add', 'tab-click', 'tab-remove'])
const navContainerRef = ref()
const navBoxRef = ref()
const activeBarStyle = reactive({})
const navOffset = ref(0)
const scrollBtnVisible = ref(false)

const scrollToActiveTab = () => {
  const navContainer = navContainerRef.value
  const navScroll = navBoxRef.value
  const activeTab = navScroll.querySelector('.is-active')

  if (!activeTab) return

  const activeTabBounding = activeTab.getBoundingClientRect()
  const navScrollBounding = navContainer.getBoundingClientRect()
  const maxOffset = navScroll.offsetWidth - navScrollBounding.width
  const currentOffset = navOffset.value
  let newOffset = currentOffset

  if (activeTabBounding.left < navScrollBounding.left) {
    newOffset =
        currentOffset - (navScrollBounding.left - activeTabBounding.left)
  }
  if (activeTabBounding.right > navScrollBounding.right) {
    newOffset =
        currentOffset + activeTabBounding.right - navScrollBounding.right
  }
  newOffset = Math.max(newOffset, 0)
  navOffset.value = Math.min(newOffset, maxOffset)
}

const handleAdd = () => {
  emits('tab-add')
  nextTick(() => {
    moveActiveBar()
    scrollToActiveTab()
  })
}
const handleRemove = id => {
  emits('tab-remove', id)
  nextTick(() => {
    moveActiveBar()
    scrollToActiveTab()
  })
}
const handleClick = id => {
  emits('tab-click', id)
  nextTick(() => scrollToActiveTab())
}
const moveActiveBar = () => {
  const id = `#tabItem${props.modelValue}`
  const activeBar = navBoxRef.value.querySelector(id)

  if (!activeBar) {
    return
  }

  const offsetLeft = activeBar.offsetLeft
  activeBarStyle.transform = `translateX(${offsetLeft}px)`
  activeBarStyle.width = `${activeBar.offsetWidth}px`
}

const scrollPrev = () => {
  if (!navContainerRef.value) return

  const containerWidth = navContainerRef.value.offsetWidth
  const curOffset = navOffset.value

  if (!curOffset) return

  const newOffset = curOffset > containerWidth ? curOffset - containerWidth : 0

  navOffset.value = newOffset
}

const scrollNext = () => {
  if (!navContainerRef.value || !navBoxRef.value) return

  const navWidth = navBoxRef.value.offsetWidth
  const containerWidth =
      navContainerRef.value.offsetWidth
  const curOffset = navOffset.value

  if (navWidth - curOffset <= containerWidth) return

  const newOffset =
      navWidth - curOffset > containerWidth * 2
          ? curOffset + containerWidth
          : navWidth - containerWidth

  navOffset.value = newOffset
}

const navScrollStyle = computed(() => {
  return {
    transform: `translateX(-${navOffset.value}px)`,
  }
})

watch(() => props.modelValue, newVal => moveActiveBar())

onUpdated(() => {
  nextTick(() => {
    const navContainerWidth = navContainerRef.value.offsetWidth
    const navBoxWidth = navBoxRef.value.offsetWidth
    scrollBtnVisible.value = navBoxWidth > navContainerWidth
  })
})
</script>

<template>
  <div class="temp-tabs">
    <div class="new-tab-btn" @click="handleAdd">+</div>
    <div class="tab-wrap">
      <div class="tab-prev" v-if="scrollBtnVisible" @click="scrollPrev">&lt;</div>
      <div class="tab-next" v-if="scrollBtnVisible" @click="scrollNext">&gt;</div>
      <div ref="navContainerRef" class="scroll-container">
        <div ref="navBoxRef" class="scroll-box" :style="navScrollStyle">
          <div class="active-bar" :style="activeBarStyle"></div>
          <div :id="`tabItem${item[idKey]}`"
               :class="['tab-item',modelValue === item[idKey] ? 'is-active': '']"
               v-for="item in tabs"
               :key="item[idKey]"
               @click="handleClick(item[idKey])"
          >
            <span>{{ item[titleKey] }}</span>
            <i class="close" @click.stop="handleRemove(item[idKey])">×</i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.temp-tabs {
  user-select: none;

  .active-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    background-color: var(--el-color-primary);
    z-index: 1;
    transition: width var(--el-transition-duration) var(--el-transition-function-ease-in-out-bezier), transform var(--el-transition-duration) var(--el-transition-function-ease-in-out-bezier);
    list-style: none;
  }

  .new-tab-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    float: right;
    border: 1px solid var(--el-border-color);
    height: 20px;
    width: 20px;
    line-height: 20px;
    margin: 10px 0 10px 10px;
    border-radius: 3px;
    text-align: center;
    font-size: 12px;
    color: var(--el-text-color-primary);
    cursor: pointer;
    transition: all .15s;
  }

  .tab-wrap {
    position: relative;
    padding: 0 20px;
    overflow: hidden;

    .tab-prev,
    .tab-next {
      position: absolute;
      cursor: pointer;
      line-height: 40px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      width: 20px;
      text-align: center;
    }

    .tab-prev {
      left: 0;
    }

    .tab-next {
      right: 0;
    }
  }

  .scroll-container {
    overflow: hidden;
  }

  .scroll-box {
    display: flex;
    white-space: nowrap;
    position: relative;
    transition: transform var(--el-transition-duration);
    float: left;
    z-index: calc(var(--el-index-normal) + 1);
  }
}

.tab-item {
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
  list-style: none;
  font-size: var(--el-font-size-base);
  font-weight: 500;
  color: var(--el-text-color-primary);
  position: relative;

  &.is-active {
    background: #ffbdbd;
  }

  .close {
    font-size: 20px;
    margin-left: 12px;
    vertical-align: middle;
    cursor: pointer;
    line-height: 0;
    margin-top: -9px;
    display: inline-block;
  }
}
</style>
